//
//  CTContactsViewController.m
//  CT
//
//  Created by liufanwei on 15/3/13.
//  Copyright (c) 2015年 liufanwei. All rights reserved.
//

#import "CTContactsViewController.h"
#import <AddressBook/AddressBook.h>
#import "CTContactsTableViewCell.h"
#import "UILabel+WBExtension.h"
#import "CommonMicro.h"
#import "UIView+WBExtension.h"
#import "CTContactTableView.h"
#import "CTContactManager.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#import "CTNetHelper.h"
#import "CTUserDefaultHelper.h"
#import "BDKNotifyHUD.h"
#import "CTContactShowItem.h"
#import "CTCallViewController.h"

@interface CTContactsViewController ()<UITableViewDelegate,
                                        UITableViewDataSource,
                                        CTContactTableViewDelegate,
                                        UIScrollViewDelegate,
                                        ABNewPersonViewControllerDelegate,
                                        UIAlertViewDelegate,
                                        UISearchBarDelegate>
{
    NSMutableDictionary * _DataDic;//所有联系人
    NSMutableArray      * _ArrKeys;//缩略键盘
    NSArray             * _SortKeys;//排序键值
    ABNewPersonViewController * _NewPersonVC;
    NSIndexPath * selectIndex;
    
    UIBarButtonItem * _ButtonAdd;
    CTContactShowItem * _SelectItem;
    UISearchBar * _SearchBar;
    UITableView * _TableView;
    BOOL ShowUserInfor;

}
@end

@implementation CTContactsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _DataDic = [[NSMutableDictionary alloc] init];
    _ArrKeys = [[NSMutableArray alloc] init];
    _SortKeys = [[NSMutableArray alloc] init];
    
    [self initData];
    [self initView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotifyCation:) name:kNotifiCationLoadContactsReply object:Nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifiCationLoadContactsReply object:Nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [_SearchBar resignFirstResponder];
    
}

-(void)viewWillAppear:(BOOL)animated{
    if (ShowUserInfor) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotifiCationLoadContactsRequest object:Nil];
        ShowUserInfor = NO;
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

-(void)onNotifyCation:(NSNotification*)sender{
    [self reloadData:Nil];
}

-(void)initView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _TableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.navigationController.navigationBar.barTintColor = kBackGroundColor;
    _TableView.alwaysBounceVertical = NO;
    _TableView.alwaysBounceHorizontal = NO;
    
    UIButton * rightbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 34)];
    [rightbutton addTarget:self action:@selector(onAddButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [rightbutton setTitle:@"新增" forState:UIControlStateNormal];
    rightbutton.clipsToBounds = YES;
    rightbutton.layer.borderColor = [UIColor whiteColor].CGColor;
    rightbutton.layer.borderWidth = 2.0;
    rightbutton.backgroundColor = kBackGroundColor;
    _ButtonAdd = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = _ButtonAdd;
    
    UILabel * leftLabel = [UILabel labelWithText:@"联系人" font:[UIFont fontWithName:kFontName size:20]];
    leftLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = leftLabel;
    
    CGRect boottmFrame = self.tabBarController.tabBar.frame;
    CTContactTableView * view = [[CTContactTableView alloc] initWithFrame:CGRectMake(kAppFrameWidth-40, _TableView.frame.origin.y, 40, boottmFrame.origin.y - _TableView.frame.origin.y)];
    view.backgroundColor = [UIColor greenColor];
    view.separatorStyle = UITableViewCellSeparatorStyleNone;
    view.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0];
    view.scrollEnabled = NO;
    view.contactTableViewDelegate = self;
    [view reloadWithData:_ArrKeys];
    [self.view addSubview:view];
    
    CGFloat x = self.view.frame.origin.x;
    CGFloat y = self.navigationController.navigationBar.frame.origin.y;
    y += self.navigationController.navigationBar.frame.size.height;
    _SearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(x, y, self.view.frame.size.width, 40)];
    _SearchBar.delegate = self;
    [self.view addSubview:_SearchBar];
    
    y += _SearchBar.frame.size.height;
    _TableView = [[UITableView alloc] initWithFrame:CGRectMake(x, y, self.view.frame.size.width, boottmFrame.origin.y - y)];
    _TableView.delegate = self;
    _TableView.dataSource = self;
    
    [self.view addSubview:_TableView];
    [self.view addSubview:view];
}

- (void)onAddButtonClick:(id)sender {
    _NewPersonVC = [[ABNewPersonViewController alloc] init];
    _NewPersonVC.newPersonViewDelegate = self;
    _NewPersonVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:_NewPersonVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString * key = [_SortKeys objectAtIndex:section];
    NSMutableArray * arr = [_DataDic objectForKey:key];
    return arr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _SortKeys.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * identifier = @"contactsTableViewCell";
    CTContactsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        NSArray * views = [[NSBundle mainBundle] loadNibNamed:@"CTContactsTableViewCellInterface" owner:Nil options:Nil];
        cell = [views objectAtIndex:0];
    }
    NSString * key = [_SortKeys objectAtIndex:indexPath.section];
    NSArray * names = [_DataDic objectForKey:key];
    CTContactShowItem * item = [names objectAtIndex:indexPath.row];
    cell.Name.text = item.Name;
    cell.Phone.text = item.PhoneNumber;
    if (item.ImageData) {
        [cell.Head setImage:[[UIImage alloc] initWithData:item.ImageData]];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc] init];
    view.backgroundColor = kRGB(247, 247, 247);
    NSString * name = [_SortKeys objectAtIndex:section];
    UILabel * label = [UILabel labelWithText:name font:[UIFont fontWithName:kFontName size:24]];
    [label setPosition:CGPointMake(5, 0)];
    [view addSubview:label];
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    selectIndex = indexPath;
    UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"" delegate:self cancelButtonTitle:@"编辑" otherButtonTitles:@"拨打", nil];
    [alertview show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString * key = [_SortKeys objectAtIndex:selectIndex.section];
    _SelectItem = [[_DataDic objectForKey:key] objectAtIndex:selectIndex.row];
    if (buttonIndex == 1) {//make call
        [self performSegueWithIdentifier:@"makecall2" sender:self];
    }else{//edit
        ShowUserInfor = YES;
        CFErrorRef error;
        NSString * str = _SelectItem.Cid;
        int32_t cid = [str intValue];
        ABAddressBookRef result = ABAddressBookCreateWithOptions(NULL, &error);
        ABRecordID recordId  = cid;
        ABPersonViewController * personViewVC = [[ABPersonViewController alloc] init];
        personViewVC.allowsEditing = YES;
        personViewVC.editing = YES;
        personViewVC.displayedPerson = ABAddressBookGetPersonWithRecordID(result, recordId);
        personViewVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:personViewVC animated:YES];
    }
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_SearchBar resignFirstResponder];
}

#pragma ABNewPersonViewController delegate
-(void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{
    [self.navigationController popViewControllerAnimated:TRUE];
    if(person){
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotifiCationLoadContactsRequest object:Nil];
    }
}

-(void)initData{
    ShowUserInfor = NO;
    for (char mychar = 'A'; mychar < 'Z'+1; mychar++) {
        NSString *key = [NSString stringWithCString:&mychar encoding:NSASCIIStringEncoding];
        key = [key substringToIndex:1];
        [_ArrKeys addObject:key];
    }
    [self reloadData:Nil];
}

-(void)buildShowData:(NSArray*)data{
    
}

-(void)onCellClicked:(NSInteger)index
{
    [_SearchBar resignFirstResponder];
    NSString * key = [_ArrKeys objectAtIndex:index];
    NSArray * arr = [_DataDic objectForKey:key];
    if (arr && arr.count > 0) {
        index = [_SortKeys indexOfObject:key];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:index];
        [_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

-(void)reloadData:(NSString*)str{
    NSArray * data;
    [_DataDic removeAllObjects];
    if (str == Nil || str.length == 0) {
        data = [[CTContactManager share] ContactArr];
    }else{
        data = [[CTContactManager share] ContactArrWithFilter:str];
    }
    for (CTContactShowItem * item in data) {
        NSMutableArray * arr = [_DataDic objectForKey:item.SortStr];
        if (arr) {
            [arr addObject:item];
        }else{
            arr = [NSMutableArray arrayWithObject:item];
            [_DataDic setValue:arr forKey:item.SortStr];
        }
    }
    _SortKeys = [_DataDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
        [_TableView reloadData];
    });

    
}

#pragma searchbar delegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self reloadData:searchText];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    CTCallViewController * dest = segue.destinationViewController;
    dest.ItemData = _SelectItem;
}


@end
